package com.gooluke.redirect.controller;

import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import com.gooluke.redirect.resolver.UrlResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/redirect")
public class RedirectController {

    @Autowired
    private UrlResolver urlResolver;

    @GetMapping("/{shortCode}")
    public ResponseEntity<Void> redirect(@PathVariable(value = "shortCode") String shortCode,
                                         HttpServletRequest request) {
        // todo
        String targetUrl = urlResolver.resolve(shortCode);
        return ResponseEntity.status(HttpStatus.FOUND)
                .location(URI.create(targetUrl))
                .header("Cache-Control", "max-age=3600")
                .build();
    }
}
